package com.alibaba.csp.sentinel.dashboard.rule.nacos;

/**
 * packageName com.alibaba.csp.sentinel.dashboard.rule.nacos.ClusterClientConfigNacosProvider
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/8/1
 * @description TODO
 */
/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.csp.sentinel.dashboard.config.NacosRuleConstants;
import com.alibaba.csp.sentinel.dashboard.domain.cluster.config.ClusterClientConfig;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 集群客户端配置 Nacos 提供者
 */
@Component("clusterClientConfigNacosProvider")
public class ClusterClientConfigNacosProvider implements DynamicRuleProvider<ClusterClientConfig> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<String, ClusterClientConfig> converter;

    @Override
    public ClusterClientConfig getRules(String appName) throws Exception {
        String config = configService.getConfig(
                appName + NacosRuleConstants.CLUSTER_CLIENT_CONFIG_DATA_ID_POSTFIX,
                NacosRuleConstants.GROUP_ID,
                3000
        );

        if (StringUtil.isEmpty(config)) {
            return new ClusterClientConfig();
        }

        return converter.convert(config);
    }
}
